package cn.tedu.boot61.controller;

import cn.tedu.boot61.mapper.UserMapper;
import cn.tedu.boot61.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {

    @Autowired(required = false)
    UserMapper mapper;

    @RequestMapping("/reg")
    public int reg(User user){
        //查询是否存在
        User u = mapper.selectByUsername(user.getUsername());
        if (u!=null){ //如果查到了数据,u不为空,说明用户名已经存在于数据库中
            return 2;//用户名已经存在
        }
        mapper.insert(user);
        return 1; //注册成功
    }
    @RequestMapping("/check")
    public int check(User user){
        User u = mapper.selectByUsername(user.getUsername());
        return u==null?1:2; //1代表用户名可用,2代表用户名已经存在
    }

    @RequestMapping("/login")
    public int login(User user, HttpSession session){
        User u = mapper.selectByUsername(user.getUsername());
        if (u!=null){
            if (u.getPassword().equals(user.getPassword())){
                //把当前登录成功的用户信息保存到/Session会话对象中
                session.setAttribute("u",u);
                return 1;
            }
            return 3;
        }
        return 2;
    }

    @RequestMapping("/currentUser")
    public User currentUser(HttpSession session){
        //从Session对象中取出当前登录的用户对象并返回给客户端
        return (User) session.getAttribute("u");
    }

    @RequestMapping("logout")
    public void logout(HttpSession session){
        //删除登录成功时保存的用户对象
        session.removeAttribute("u");
    }

}
